package com.yadang.xml;

import java.io.StringWriter;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import org.w3c.dom.Document;

public class XmlToString {
    public static void main(String[] args) {
        try {
            // 创建DocumentBuilderFactory对象
            DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();

            // 创建DocumentBuilder对象
            DocumentBuilder builder = factory.newDocumentBuilder();

            // 解析XML文件，生成Document对象
            Document doc = builder.parse("D:\\IDEA_Workspaces\\YadangDayDayUp\\baseKnowledge\\src\\main\\java\\com\\yadang\\xml\\1.xml");

            // 创建TransformerFactory对象
            TransformerFactory transformerFactory = TransformerFactory.newInstance();

            // 创建Transformer对象
            Transformer transformer = transformerFactory.newTransformer();

            // 设置Transformer的属性
            transformer.setOutputProperty("indent", "yes");
            transformer.setOutputProperty("encoding", "UTF-8");

            // 创建DOMSource对象
            DOMSource source = new DOMSource(doc);

            // 创建StringWriter对象
            StringWriter writer = new StringWriter();

            // 创建StreamResult对象
            StreamResult result = new StreamResult(writer);

            // 将DOM对象转换为字符串
            transformer.transform(source, result);

            // 输出字符串
            System.out.println(writer.toString());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
